package com.Bigbluebook.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.Bigbluebook.ClickEvent.ButtonClickListener;
import com.Bigbluebook.R;
import com.Bigbluebook.Service.CommentActionListener;
import com.Bigbluebook.Service.CommentApiService;
import com.Bigbluebook.Service.LikeApiService;
import com.Bigbluebook.Service.PostApiService;
import com.Bigbluebook.Service.StarApiService;
import com.Bigbluebook.adapter.CommentAdapter;
import com.Bigbluebook.entity.Comment;
import com.Bigbluebook.entity.Like;
import com.Bigbluebook.entity.LikeStatus;
import com.Bigbluebook.entity.Post;
import com.Bigbluebook.entity.PostsInfo;
import com.Bigbluebook.entity.Star;
import com.Bigbluebook.entity.User;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostDetailsActivity extends AppCompatActivity implements CommentActionListener {
    private TextView author, content, createdAt;
    private RecyclerView recyclerView;
    private RecyclerView recyclerView_hide;
    private CommentAdapter commentAdapter;
    private PostApiService postApiService = new PostApiService();
    private CommentApiService commentApiService = new CommentApiService();
    private LikeApiService likeApiService = new LikeApiService();
    private StarApiService starApiService = new StarApiService();
    private int postId;  // 用于存储从 Intent 中传递过来的 postId
    private PostsInfo postInfo;
    private List<Comment> commentsList = new ArrayList<>();
    private Button btnSendComment;
    private Button btnfollow;
    private EditText btnComment;
    private ImageButton btnLike;
    private ImageButton btnStar;
    private ImageButton btnShare;
    private ImageButton btnViewComments;
    private ImageButton btnLikeComment;
    private ImageButton btnReplyComment;
    private boolean isLiked;
    private int likeId;
    private boolean isStared;
    private int starId;
    private ButtonClickListener buttonClickListener;
    private TextView btnLikeCount;
    private TextView btnStarCount;
    private TextView btnCommentsCount;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_details);

        //获取Intent传递的postId
        postId = getIntent().getIntExtra("postId", -1);

        //初始化UI
        author = findViewById(R.id.tvUserName);
        content = findViewById(R.id.PostContent);
        //createdAt = findViewById(R.id.create_time);
        recyclerView = findViewById(R.id.recyclerComments);
        //recyclerView_hide = findViewById(R.id.recyclerComments_hide);
        btnSendComment = findViewById(R.id.btnSendComment);
        btnComment = findViewById(R.id.btnComment);
        btnfollow = findViewById(R.id.btnFollow);
        btnLike = findViewById(R.id.btnLike);
        btnStar = findViewById(R.id.btnStar);
        btnShare = findViewById(R.id.btnShare);
        btnLikeCount = findViewById(R.id.btnLikeCount);
        btnStarCount = findViewById(R.id.btnStarCount);
        //btnCommentsCount = findViewById(R.id.btnCommentsCount);
        //btnViewComments =findViewById(R.id.btnViewComments);

        //初始化评论RecyclerView
        commentAdapter = new CommentAdapter(commentsList,this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(commentAdapter);

        //初始化ApiService
        postApiService = new PostApiService();
        commentApiService = new CommentApiService();
        likeApiService = new LikeApiService();

        //加载帖子信息
        loadPostData();

        //加载评论信息
        loadCommentsData();

        //加载点赞状态
        loadLikeStatus();

        //加载点赞数和收藏数
        loadInitialCounts();

        //设置点击监听器
        Intent intent = getIntent();
        if (intent != null) {
            //确保Intent不为空后再传递给ButtonClickListener
            buttonClickListener = new ButtonClickListener(this, intent);
        } else {
            Log.e("PostDetailsActivity", "Intent is null when creating ButtonClickListener");
        }
        btnfollow.setOnClickListener(buttonClickListener);

        //设置发送按钮点击事件
        btnSendComment.setOnClickListener(v -> {
            String commentContent = btnComment.getText().toString().trim();
            if (!commentContent.isEmpty()) {
                Log.e("PostDetailsActivity","评论内容是" + String.valueOf(commentContent));
                sendComment(commentContent);
                btnComment.setText(""); //清空输入框
            }
        });

        //添加键盘事件监听器
        btnComment.setOnKeyListener((v, keyCode, event) -> {
            if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER){
                String commentContent = btnComment.getText().toString().trim();
                if (!commentContent.isEmpty()) {
                    Log.e("PostDetailsActivity","评论内容是" + String.valueOf(commentContent));
                    sendComment(commentContent);
                    btnComment.setText(""); //清空输入框
                    return true; //消费事件
                }
            }
            return false;
        });

        //设置博文按钮点击事件
        btnLike.setOnClickListener(v -> toggleLike());
        btnStar.setOnClickListener(v -> toggleStar());
        btnShare.setOnClickListener(v -> toggleShare());

//        //设置显示/隐藏评论列表
//        btnViewComments.setOnClickListener(V ->{
//            if(recyclerView_hide.getVisibility() == View.GONE){
//                //显示评论
//                recyclerView_hide.setVisibility(View.VISIBLE);
//                loadCommentsData();
//            } else {
//                recyclerView_hide.setVisibility(View.GONE);
//            }
//        });
    }

    //加载帖子数据
    private void loadPostData() {
        postApiService.getPostById(postId, new Callback<PostsInfo>() {
            @Override
            public void onResponse(Call<PostsInfo> call, Response<PostsInfo> response) {
                if (response.isSuccessful() && response.body() != null) {
                    postInfo = response.body();
                    author.setText(postInfo.getUser().getUsername());

                    content.setText(postInfo.getContent());
                    //createdAt.setText(postInfo.getCreatedAt());
                    System.out.println(response.body());
                    System.out.println(response.code());
                    Log.e("PostDetailsActivity", "帖子加载成功");
                } else {
                    Log.e("PostDetailsActivity", "帖子加载失败");
                }
            }

            @Override
            public void onFailure(Call<PostsInfo> call, Throwable t) {
                Log.e("PostDetailsActivity", "网络请求失败: " + t.getMessage());
            }
        });
    }

    //加载评论数据
    private void loadCommentsData() {
        Post post = new Post();
        post.setId(postId);
        postApiService.getCommentsByPostId(postId, new Callback<List<Comment>>() {
            @Override
            public void onResponse(Call<List<Comment>> call, Response<List<Comment>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    commentsList = response.body();
                    commentAdapter.setCommentsList(commentsList);
                    Log.e("PostDetailsActivity", "评论加载成功");
                } else {
                    Log.e("PostDetailsActivity", "评论加载失败");
                }
            }

            @Override
            public void onFailure(Call<List<Comment>> call, Throwable t) {
                Log.e("PostDetailsActivity", "网络请求失败: " + t.getMessage());
            }
        });
    }

    //发送评论
    public void sendComment(String commentContent) {

        //从SharedPreferences获取userId
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1); // 默认值为 -1，表示未找到

        if (userId == -1) {
            Log.e("PostDetailsActivity", "用户未登录或ID未找到");
            return;
        }
        Post post  = new Post();
        post.setId(postId);
        User user = new User();
        user.setId(userId);
        //创建新评论对象
        Comment newComment = new Comment(post, user, commentContent);

        //调用API创建评论
        commentApiService.createComment(newComment, new Callback<Comment>() {
            @Override
            public void onResponse(Call<Comment> call, Response<Comment> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Log.e("PostDetailsActivity","评论发送成功");
                    btnComment.setText("");
                    loadCommentsData();
                } else {
                    Log.e("PostDetailsActivity", "评论发送失败");
                }
            }

            @Override
            public void onFailure(Call<Comment> call, Throwable t) {
                Log.e("PostDetailsActivity", "评论发送失败: " + t.getMessage());
            }
        });
    }

    //实现评论点赞
    public void onLikeComment(Comment comment){
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);


        User user = new User();
        user.setId(userId);

        Like like = new Like();
        like.setComment(comment);
        like.setUser(user);

        if (isLiked) {
            // 取消评论点赞
            likeApiService.unlikeComment(likeId, new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    if (response.isSuccessful()) {
                        isLiked = false;
                        updateLikeButton(); //更新按钮状态
                        Toast.makeText(PostDetailsActivity.this, "取消评论点赞成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "取消评论点赞失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                    Log.e("PostDetailsActivity", "取消评论点赞失败: " + t.getMessage());
                }
            });
        } else {
            // 点赞
            likeApiService.likeComment(like, new Callback<Like>() {
                @Override
                public void onResponse(Call<Like> call, Response<Like> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        likeId = response.body().getId();
                        isLiked = true;
                        updateLikeButton(); //更新按钮状态
                        Toast.makeText(PostDetailsActivity.this, "评论点赞成功", Toast.LENGTH_SHORT).show();
                        saveLikeStatus(); //保存状态
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "评论点赞失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Like> call, Throwable t) {
                    Log.e("PostDetailsActivity", "评论点赞失败: " + t.getMessage());
                }
            });
        }
    }

    //实现弹出对话框获取回复内容
    public void onReplyToComment(Comment comment){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("回复评论");

        final EditText input = new EditText(this);
        builder.setView(input);

        builder.setPositiveButton("发送",(dialog, which) -> {
           String replyContent = input.getText().toString().trim();
           if(!replyContent.isEmpty()){
               sendReply(comment, replyContent);
           }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    //实现评论回复
    public void sendReply(Comment comment, String replyContent){
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);

        //创建回复对象
        Comment reply = new Comment();
        reply.setContent(replyContent);

        User user = new User();
        user.setId(userId);
        reply.setUser(user);

        //调用API创建评论
        commentApiService.createComment(reply, new Callback<Comment>() {
            @Override
            public void onResponse(Call<Comment> call, Response<Comment> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Log.e("PostDetailsActivity","回复成功");
                    btnComment.setText("");
                    loadCommentsData();
                } else {
                    Log.e("PostDetailsActivity", "回复失败");
                }
            }

            @Override
            public void onFailure(Call<Comment> call, Throwable t) {
                Log.e("PostDetailsActivity", "回复发送失败: " + t.getMessage());
            }
        });
    }

    //实现博文点赞
    private void toggleLike() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);

        Post post = new Post();
        post.setId(postId);
        User user = new User();
        user.setId(userId);

        Like like = new Like();
        like.setPost(post);
        like.setUser(user);

        if (isLiked) {
            // 取消点赞
            likeApiService.unlikePost(likeId, new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    if (response.isSuccessful()) {
                        isLiked = false;
                        updateLikeButton(); //更新按钮状态
                        long newCount = Long.parseLong(btnLikeCount.getText().toString()) - 1;//点赞数-1
                        btnLikeCount.setText(String.valueOf(newCount));
                        Toast.makeText(PostDetailsActivity.this, "取消点赞成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "取消点赞失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                    Log.e("PostDetailsActivity", "取消点赞失败: " + t.getMessage());
                }
            });
        } else {
            // 点赞
            likeApiService.likePost(like, new Callback<Like>() {
                @Override
                public void onResponse(Call<Like> call, Response<Like> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        likeId = response.body().getId();
                        isLiked = true;
                        updateLikeButton(); //更新按钮状态
                        long newCount = Long.parseLong(btnLikeCount.getText().toString()) + 1;//点赞数+1
                        btnLikeCount.setText(String.valueOf(newCount));
                        Toast.makeText(PostDetailsActivity.this, "点赞成功", Toast.LENGTH_SHORT).show();
                        saveLikeStatus(); //保存状态
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "点赞失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Like> call, Throwable t) {
                    Log.e("PostDetailsActivity", "点赞失败: " + t.getMessage());
                }
            });
        }
    }

    //实现收藏
    private void toggleStar() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);

        Post post = new Post();
        post.setId(postId);
        User user = new User();
        user.setId(userId);

        Star star = new Star();
        star.setPost(post);
        star.setUser(user);

        if (isStared) {
            //取消收藏
            starApiService.unstarPost(starId, new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    if (response.isSuccessful()) {
                        isStared = false;
                        updateStarButton(); //更新按钮状态
                        long newCount = Long.parseLong(btnStarCount.getText().toString()) - 1;//收藏数-1
                        btnStarCount.setText(String.valueOf(newCount));
                        Toast.makeText(PostDetailsActivity.this, "取消收藏成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "取消收藏失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                    Log.e("PostDetailsActivity", "取消收藏失败: " + t.getMessage());
                }
            });
        } else {
            //收藏
            starApiService.starPost(star, new Callback<Star>() {
                @Override
                public void onResponse(Call<Star> call, Response<Star> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        starId = response.body().getId();
                        isStared = true;
                        updateStarButton(); //更新按钮状态
                        long newCount = Long.parseLong(btnStarCount.getText().toString()) + 1;//收藏数+1
                        btnStarCount.setText(String.valueOf(newCount));
                        Toast.makeText(PostDetailsActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        saveStarStatus(); //保存状态
                    } else {
                        Toast.makeText(PostDetailsActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Star> call, Throwable t) {
                    Log.e("PostDetailsActivity", "收藏失败: " + t.getMessage());
                }
            });
        }
    }

    //实现分享
    private void toggleShare(){
        String shareText = "分享博文: " + postInfo.getContent();//获取博文内容
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        startActivity(Intent.createChooser(shareIntent, "分享博文"));
    }

    //加载点赞状态
    private void loadLikeStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);

        likeApiService.checkLikeStatus(postId, userId, new Callback<LikeStatus>() {
            @Override
            public void onResponse(Call<LikeStatus> call, Response<LikeStatus> response) {
                if (response.isSuccessful() && response.body() != null) {
                    isLiked = response.body().isLiked();
                    likeId = response.body().getLikeId(); // 更新点赞 ID
                } else {
                    isLiked = false; // 默认状态
                    likeId = -1; // 默认点赞 ID
                    updateLikeButton(); // 更新按钮状态
                    saveLikeStatus(); // 保存状态
                }
            }

            @Override
            public void onFailure(Call<LikeStatus> call, Throwable t) {
                Log.e("PostDetailsActivity", "加载点赞状态失败: " + t.getMessage());
                loadSavedLikeStatus();
            }
        });
    }

    private void loadSavedLikeStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        isLiked = sharedPreferences.getBoolean("isLiked", false);
        likeId = sharedPreferences.getInt("likeId", -1);
        updateLikeButton(); // 更新按钮状态
        saveLikeStatus(); // 保存状态
    }

    private void saveLikeStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("likeId", likeId);
        editor.putBoolean("isLiked", isLiked);
        editor.apply();
        Log.e("PostDetailsActivity","点赞状态s " + isLiked);
        Log.e("PostDetailsActivity","点赞IDs" + likeId);
    }

    private void updateLikeButton() {
        if (isLiked) {
            btnLike.setImageResource(R.drawable.baseline_favorite_24);
        } else {
            btnLike.setImageResource(R.drawable.baseline_favorite_border_24);
        }
    }

    private void saveStarStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("starId", starId);
        editor.putBoolean("isStared", isStared);
        editor.apply();
        Log.e("PostDetailsActivity","收藏状态s " + isStared);
        Log.e("PostDetailsActivity","收藏IDs" + starId);
    }

    private void updateStarButton() {
        if (isStared) {
            btnStar.setImageResource(R.drawable.baseline_star_24);
        } else {
            btnStar.setImageResource(R.drawable.baseline_star_border_24);
        }
    }

    //加载初始计数
    private void loadInitialCounts() {
        postApiService.getLikesCount(postId, new Callback<Long>() {
            @Override
            public void onResponse(Call<Long> call, Response<Long> response) {
                if (response.isSuccessful() && response.body() != null) {
                    btnLikeCount.setText(String.valueOf(response.body()));
                }
            }

            @Override
            public void onFailure(Call<Long> call, Throwable t) {
                Log.e("PostDetailsActivity", "获取点赞数失败: " + t.getMessage());
            }
        });

        postApiService.getStarsCount(postId, new Callback<Long>() {
            @Override
            public void onResponse(Call<Long> call, Response<Long> response) {
                if (response.isSuccessful() && response.body() != null) {
                    btnStarCount.setText(String.valueOf(response.body()));
                }
            }

            @Override
            public void onFailure(Call<Long> call, Throwable t) {
                Log.e("PostDetailsActivity", "获取收藏数失败: " + t.getMessage());
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveLikeStatus();
    }
}
